<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\Database\Model\Events\Deleted;
use Hyperf\Database\Model\Events\Saved;
use Hyperf\Database\Model\Relations\Pivot;

/**
 * @property int $id 
 * @property int $user_id 用户ID
 * @property int $article_id 文章ID
 * @property-read User $user
 * @property-read Article $article
 * @property \Carbon\Carbon $created_at 
 */
class ArticleLike extends Pivot
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'article_likes';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['id', 'user_id', 'article_id', 'created_at'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'user_id' => 'integer', 'article_id' => 'integer', 'created_at' => 'datetime'];

    const UPDATED_AT = null;

    public function article()
    {
        return $this->belongsTo(Article::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function created(Saved $event)
    {
        $model = $event->getModel();
        $model->article->like_count += 1;
        $model->article->save();
    }

    public function deleted(Deleted $event)
    {
        $model = $event->getModel();
        $model->article->like_count -= 1;
        $model->article->save();
    }
}